import userApi from "@/api/sys/user";
//全局变量
import APP_CONFIG from "@/config/config";

let path = APP_CONFIG.VUE_APP_API_HOST_DEFAULT+'/websocket'
// let path = 'ws://localhost:2200/renwushu/websocket'
let URL = path

if (URL.indexOf("http") > -1){
    URL = URL.replace("http", "ws")
}
if (URL.indexOf("https") > -1){
    URL = URL.replace("https", "wss")
}
let timer = null
let ws = null
let isConnect = false
let checkHeart = 'check-heart'
let count = 0
let userInfo = {}

// 心跳检测
let heart = {
    timer: null,
    timeout: 20000, // 每20s进行一次心跳检测
    start() {
        this.timer = setTimeout(() => {
            if (isConnect) ws.send(JSON.stringify(checkHeart))
        }, this.timeout)
    },
    reset() {
        clearTimeout(this.timer)
        this.start()
    },
    close() {
        clearTimeout(this.timer)
    }
}

// WebSocket连接
const connectWebsocket = async () => {
    let token = uni.getStorageSync("javawebtoken")

    if (token) {
        if (!userInfo || !userInfo.id) {
            URL += token ? "/" + token : "/ "
            URL += "/ / "
            await userApi.getUserInfo().then(res => {
                userInfo = res.data
                URL += userInfo ? userInfo.id ? "/" + userInfo.id : "/ " : "/ "
            })
        }
        if (count > 5) {
            connectCount()
            return
        }
        try { // 正在建立连接
            // #ifdef H5
            ws = new WebSocket(URL)
            // #endif
            // #ifdef APP-PLUS
            ws = uni.connectSocket({
                url: URL,
                complete: ()=> {}
            });
            // #endif
            initWebSocket() // 初始化WebSocket连接
        } catch (e){ // 建立连接出错，重新连接
            uni.showToast({icon: 'none',position: 'bottom', title:'建立连接出错，重新连接' + e})
            connect()
        }
    }
}

// 重新连接WebSocket
function connect() {
    if (isConnect) return
	uni.showToast({icon: 'none',position: 'bottom', title:'尝试重新连接WebSocket'})
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => { // 每次连接 延迟5s
        count++
        connectWebsocket()
    }, 5000)
}

// 初始化WebSocket连接
function initWebSocket() {
    // #ifdef APP-PLUS
    ws.onOpen (function (e) { // WebSocket连接成功
        isConnect = true
        connectStatus(true)
        heart.start()
        uni.showToast({icon: 'success',position: 'bottom', title:'WebSocket连接成功'})
    })
    ws.onError(function () { // WebSocket连接发生错误
        uni.showToast({icon: 'none',position: 'bottom', title:'WebSocket连接发生错误,正在尝试重新连接'})
        isConnect = false
        connectStatus(false)
        connect()
    })
    ws.onClose(function (e) { // 已关闭WebSocket连接
        isConnect = false
        connectStatus(false)
        heart.close() // 关闭心跳检测
        uni.showToast({icon: 'success',position: 'bottom', title:'已关闭WebSocket连接'})
    })
    ws.onMessage(function (e) { // 接收到服务端发送的数据
        heart.reset() // 重置心跳检测
        if (e.data === checkHeart) return // 心跳检测
        receive(e.data)
    })
    // #endif
    // #ifdef H5
    ws.onopen = function () { // WebSocket连接成功
        isConnect = true
        connectStatus(true)
        heart.start()
		uni.showToast({icon: 'success',position: 'bottom', title:'WebSocket连接成功'})
    }
    ws.onerror = function () { // WebSocket连接发生错误
        uni.showToast({icon: 'none',position: 'bottom', title:'WebSocket连接发生错误,正在尝试重新连接'})
        isConnect = false
        connectStatus(false)
        connect()
    }
    ws.onclose = function (e) { // 已关闭WebSocket连接
        isConnect = false
        connectStatus(false)
        heart.close() // 关闭心跳检测
		uni.showToast({icon: 'success',position: 'bottom', title:'已关闭WebSocket连接'})
    }
    ws.onmessage = function (e) { // 接收到服务端发送的数据
        heart.reset() // 重置心跳检测
        if (e.data === checkHeart) return // 心跳检测
        receive(e.data)
    }
    // #endif
}

function connectCount() {
	uni.showToast({icon: 'none',position: 'bottom', title:'WebSocket连接失败'})
    clearTimeout(timer)
}

// 发送消息
const webSocketSend = (data) => {
    let code = ws?.readyState
    switch (code) {
        case 1:
            sendSock(data)
            break;
        case 2:
			uni.showToast({icon: 'none',position: 'bottom', title:'WebSocket连接正在关闭中,请重新连接后再发送消息'})
            break;
        default:
			uni.showToast({icon: 'none',position: 'bottom', title:'请先建立WebSocket连接'})
            break;
    }
}

function sendSock(data) {
    ws.send(JSON.stringify(data))
	uni.showToast({icon: 'success',position: 'bottom', title:'消息发送成功'})
}

// 关闭连接
const closeWebSocket = () => {
    if (isConnection()) {
        ws.close()
        // URL = path
    }
}

// 是否已连接
function isConnection() {
    return ws?.readyState === 1
}

// 自定义事件
function receive(data) {
    uni.$emit('receive',{detail: data});
    uni.$emit('receiveMess',{detail: data});
    uni.$emit('receiveChat',{detail: data});
}

function connectStatus(status) {
    uni.$emit('connectStatus',{detail: status});
}

export default {
    connectWebsocket,
    closeWebSocket,
    webSocketSend,
    isConnection
}